package com.campus.help.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.help.common.Result;
import com.campus.help.dto.MerchantLoginDTO;
import com.campus.help.entity.Merchant;
import com.campus.help.mapper.MerchantMapper;
import com.campus.help.service.MerchantService;
import com.campus.help.utils.JwtUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


/**
 * 商户服务实现类
 */
@Slf4j
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private com.campus.help.mapper.LaborMapper laborMapper;
    
    @Autowired
    private com.campus.help.mapper.LaborTypeMapper laborTypeMapper;



    private static final String SALT = "campus-help-merchant-salt";

    @Override
    public Result login(MerchantLoginDTO loginDTO) {
        // 参数验证
        if (!StringUtils.hasText(loginDTO.getUsername()) || !StringUtils.hasText(loginDTO.getPassword())) {
            return Result.error("用户名和密码不能为空");
        }
        
        // 根据用户名查询商户
        Merchant merchant = merchantMapper.selectByUsername(loginDTO.getUsername());
        if (merchant == null) {
            return Result.error("用户名或密码错误");
        }
        
        // 验证密码
        String encryptedPassword = encryptPassword(loginDTO.getPassword());
        if (!encryptedPassword.equals(merchant.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        
        // 检查账号状态
        if (merchant.getStatus() != 1) {
            return Result.error("账户已被禁用，请联系管理员");
        }
        
        try {
            // 生成JWT token
            String token = jwtUtils.generateMerchantToken(merchant.getId(), merchant.getUsername());
            
            // 更新最后登录时间
            updateLoginInfo(merchant.getId());
            
            // 返回登录结果
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userInfo", buildMerchantInfo(merchant));
            
            return Result.success("登录成功", data);
            
        } catch (Exception e) {
            log.error("商户登录失败", e);
            return Result.error("登录失败，请稍后重试");
        }
    }

    @Override
    public Merchant getByUsername(String username) {
        return merchantMapper.selectByUsername(username);
    }

    @Override
    public void updateLoginInfo(Long merchantId) {
        try {
            merchantMapper.updateLoginInfo(merchantId, LocalDateTime.now());
        } catch (Exception e) {
            log.error("更新商户登录信息失败: merchantId={}", merchantId, e);
        }
    }

    /**
     * 构建商户信息（脱敏）
     */
    private Map<String, Object> buildMerchantInfo(Merchant merchant) {
        Map<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("id", merchant.getId());
        merchantInfo.put("username", merchant.getUsername());
        merchantInfo.put("merchantName", merchant.getMerchantName());
        merchantInfo.put("contactPerson", merchant.getContactPerson());
        merchantInfo.put("phone", merchant.getPhone());
        merchantInfo.put("email", merchant.getEmail());
        merchantInfo.put("avatar", merchant.getAvatar());
        merchantInfo.put("status", merchant.getStatus());
        merchantInfo.put("userType", "merchant");
        return merchantInfo;
    }
    
    @Override
    public Page<com.campus.help.vo.MerchantLaborVO> getMerchantLabors(
            Long merchantId, int page, int size, String jobTitle, Long typeId, String workType, String status) {
        Page<com.campus.help.entity.Labor> pageParam = new Page<>(page, size);
        
        QueryWrapper<com.campus.help.entity.Labor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchant_id", merchantId);
        
        // 添加搜索条件
        if (jobTitle != null && !jobTitle.trim().isEmpty()) {
            queryWrapper.like("job_title", jobTitle);
        }
        if (typeId != null) {
            queryWrapper.eq("type_id", typeId);
        }
        if (workType != null && !workType.trim().isEmpty()) {
            queryWrapper.eq("work_type", workType);
        }
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<com.campus.help.entity.Labor> laborPage = laborMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        Page<com.campus.help.vo.MerchantLaborVO> voPage = new Page<>();
        voPage.setCurrent(laborPage.getCurrent());
        voPage.setSize(laborPage.getSize());
        voPage.setTotal(laborPage.getTotal());
        voPage.setPages(laborPage.getPages());
        
        java.util.List<com.campus.help.vo.MerchantLaborVO> voList = laborPage.getRecords().stream()
            .map(this::convertToVO)
            .collect(java.util.stream.Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }
    
    /**
     * 转换Labor实体为MerchantLaborVO
     */
    private com.campus.help.vo.MerchantLaborVO convertToVO(com.campus.help.entity.Labor labor) {
        com.campus.help.vo.MerchantLaborVO vo = new com.campus.help.vo.MerchantLaborVO();
        vo.setId(labor.getId());
        vo.setTypeId(labor.getTypeId());
        
        // 查询劳务类型名称
        if (labor.getTypeId() != null) {
            com.campus.help.entity.LaborType laborType = laborTypeMapper.selectById(labor.getTypeId());
            if (laborType != null) {
                vo.setTypeName(laborType.getTypeName());
            }
        }
        
        vo.setJobTitle(labor.getJobTitle());
        vo.setLocation(labor.getLocation());
        vo.setWorkType(labor.getWorkType());
        vo.setSalary(labor.getSalary());
        vo.setDescription(labor.getDescription());
        vo.setRequirements(labor.getRequirements());
        vo.setPhone(labor.getPhone());
        vo.setStatus(labor.getStatus());
        vo.setUrgent(labor.getUrgent());
        vo.setViewCount(labor.getViewCount());
        vo.setApplyCount(labor.getApplyCount());
        vo.setRequiredCount(labor.getRequiredCount());
        vo.setAcceptedCount(labor.getAcceptedCount());
        vo.setCreateTime(labor.getCreateTime());
        vo.setUpdateTime(labor.getUpdateTime());
        return vo;
    }
    
    /**
     * 密码加密
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex((password + SALT).getBytes());
    }
    
    @Override
    public boolean changePassword(Long merchantId, String oldPassword, String newPassword) {
        try {
            // 根据商户ID查询商户信息
            Merchant merchant = merchantMapper.selectById(merchantId);
            if (merchant == null) {
                log.error("商户不存在: merchantId={}", merchantId);
                return false;
            }
            
            // 验证旧密码
            String encryptedOldPassword = encryptPassword(oldPassword);
            if (!encryptedOldPassword.equals(merchant.getPassword())) {
                log.warn("旧密码错误: merchantId={}", merchantId);
                return false;
            }
            
            // 加密新密码
            String encryptedNewPassword = encryptPassword(newPassword);
            
            // 更新密码
            merchant.setPassword(encryptedNewPassword);
            merchant.setUpdateTime(LocalDateTime.now());
            int updateCount = merchantMapper.updateById(merchant);
            
            if (updateCount > 0) {
                log.info("商户密码修改成功: merchantId={}", merchantId);
                return true;
            } else {
                log.error("商户密码修改失败: merchantId={}", merchantId);
                return false;
            }
            
        } catch (Exception e) {
            log.error("修改商户密码异常: merchantId={}", merchantId, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getMerchantStats(Long merchantId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 统计已发布的劳务数（招聘中的）
            QueryWrapper<com.campus.help.entity.Labor> recruitingWrapper = new QueryWrapper<>();
            recruitingWrapper.eq("merchant_id", merchantId)
                           .eq("status", "recruiting");
            Long publishedLabors = laborMapper.selectCount(recruitingWrapper);
            
            // 统计待审核的劳务数
            QueryWrapper<com.campus.help.entity.Labor> pendingWrapper = new QueryWrapper<>();
            pendingWrapper.eq("merchant_id", merchantId)
                        .eq("status", "pending");
            Long pendingLabors = laborMapper.selectCount(pendingWrapper);
            
            // 统计已完成的劳务数
            QueryWrapper<com.campus.help.entity.Labor> completedWrapper = new QueryWrapper<>();
            completedWrapper.eq("merchant_id", merchantId)
                          .eq("status", "completed");
            Long completedLabors = laborMapper.selectCount(completedWrapper);
            
            // 统计总申请数（所有劳务的申请数总和）
            QueryWrapper<com.campus.help.entity.Labor> allLaborsWrapper = new QueryWrapper<>();
            allLaborsWrapper.eq("merchant_id", merchantId);
            java.util.List<com.campus.help.entity.Labor> allLabors = laborMapper.selectList(allLaborsWrapper);
            
            Long totalApplications = allLabors.stream()
                .mapToLong(labor -> labor.getApplyCount() != null ? labor.getApplyCount() : 0L)
                .sum();
            
            // 统计总劳务数
            Long totalLabors = laborMapper.selectCount(allLaborsWrapper);
            
            stats.put("publishedLabors", publishedLabors);
            stats.put("pendingLabors", pendingLabors);
            stats.put("completedLabors", completedLabors);
            stats.put("totalApplications", totalApplications);
            stats.put("totalLabors", totalLabors);
            
            log.info("获取商户统计信息成功: merchantId={}, stats={}", merchantId, stats);
            
        } catch (Exception e) {
            log.error("获取商户统计信息异常: merchantId={}", merchantId, e);
            // 返回默认值
            stats.put("publishedLabors", 0L);
            stats.put("pendingLabors", 0L);
            stats.put("completedLabors", 0L);
            stats.put("totalApplications", 0L);
            stats.put("totalLabors", 0L);
        }
        
        return stats;
    }
    
    @Override
    public com.campus.help.entity.Labor publishLabor(com.campus.help.entity.Labor labor, Long merchantId) {
        try {
            // 设置商户相关信息
            labor.setMerchantId(merchantId);
            labor.setPublisherId(merchantId);
            labor.setPublisherType("merchant");
            
            // 设置初始状态
            labor.setStatus("recruiting");
            labor.setViewCount(0);
            labor.setApplyCount(0);
            labor.setAcceptedCount(0);
            
            // 设置时间
            labor.setCreateTime(LocalDateTime.now());
            labor.setUpdateTime(LocalDateTime.now());
            
            // 保存到数据库
            int insertCount = laborMapper.insert(labor);
            
            if (insertCount > 0) {
                log.info("商户发布劳务成功: merchantId={}, laborId={}, jobTitle={}", 
                    merchantId, labor.getId(), labor.getJobTitle());
                return labor;
            } else {
                log.error("商户发布劳务失败: merchantId={}", merchantId);
                throw new RuntimeException("发布劳务失败");
            }
            
        } catch (Exception e) {
            log.error("商户发布劳务异常: merchantId={}", merchantId, e);
            throw new RuntimeException("发布劳务失败: " + e.getMessage());
        }
    }
    
    @Override
    public com.campus.help.entity.Labor updateLabor(com.campus.help.entity.Labor labor, Long merchantId) {
        try {
            // 验证劳务是否存在且属于该商户
            com.campus.help.entity.Labor existingLabor = laborMapper.selectById(labor.getId());
            if (existingLabor == null) {
                log.error("劳务不存在: laborId={}", labor.getId());
                throw new RuntimeException("劳务不存在");
            }
            
            if (!merchantId.equals(existingLabor.getMerchantId())) {
                log.error("无权操作该劳务: merchantId={}, laborId={}, laborMerchantId={}", 
                    merchantId, labor.getId(), existingLabor.getMerchantId());
                throw new RuntimeException("无权操作该劳务");
            }
            
            // 更新时间
            labor.setUpdateTime(LocalDateTime.now());
            
            // 保留一些不能修改的字段
            labor.setMerchantId(existingLabor.getMerchantId());
            labor.setPublisherId(existingLabor.getPublisherId());
            labor.setPublisherType(existingLabor.getPublisherType());
            labor.setCreateTime(existingLabor.getCreateTime());
            labor.setViewCount(existingLabor.getViewCount());
            labor.setApplyCount(existingLabor.getApplyCount());
            labor.setAcceptedCount(existingLabor.getAcceptedCount());
            
            // 更新到数据库
            int updateCount = laborMapper.updateById(labor);
            
            if (updateCount > 0) {
                log.info("商户更新劳务成功: merchantId={}, laborId={}", merchantId, labor.getId());
                return labor;
            } else {
                log.error("商户更新劳务失败: merchantId={}, laborId={}", merchantId, labor.getId());
                throw new RuntimeException("更新劳务失败");
            }
            
        } catch (Exception e) {
            log.error("商户更新劳务异常: merchantId={}, laborId={}", merchantId, labor.getId(), e);
            throw new RuntimeException("更新劳务失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean closeLabor(Long laborId, Long merchantId) {
        try {
            // 验证劳务是否存在且属于该商户
            com.campus.help.entity.Labor labor = laborMapper.selectById(laborId);
            if (labor == null) {
                log.error("劳务不存在: laborId={}", laborId);
                return false;
            }
            
            if (!merchantId.equals(labor.getMerchantId())) {
                log.error("无权操作该劳务: merchantId={}, laborId={}, laborMerchantId={}", 
                    merchantId, laborId, labor.getMerchantId());
                return false;
            }
            
            // 更新状态为已关闭
            labor.setStatus("closed");
            labor.setUpdateTime(LocalDateTime.now());
            
            int updateCount = laborMapper.updateById(labor);
            
            if (updateCount > 0) {
                log.info("商户关闭劳务成功: merchantId={}, laborId={}", merchantId, laborId);
                return true;
            } else {
                log.error("商户关闭劳务失败: merchantId={}, laborId={}", merchantId, laborId);
                return false;
            }
            
        } catch (Exception e) {
            log.error("商户关闭劳务异常: merchantId={}, laborId={}", merchantId, laborId, e);
            return false;
        }
    }
    
    @Override
    public com.campus.help.entity.Labor getLaborDetail(Long laborId, Long merchantId) {
        try {
            // 查询劳务详情
            com.campus.help.entity.Labor labor = laborMapper.selectById(laborId);
            if (labor == null) {
                log.error("劳务不存在: laborId={}", laborId);
                return null;
            }
            
            // 验证是否属于该商户
            if (!merchantId.equals(labor.getMerchantId())) {
                log.error("无权访问该劳务: merchantId={}, laborId={}, laborMerchantId={}", 
                    merchantId, laborId, labor.getMerchantId());
                return null;
            }
            
            log.info("获取劳务详情成功: merchantId={}, laborId={}", merchantId, laborId);
            return labor;
            
        } catch (Exception e) {
            log.error("获取劳务详情异常: merchantId={}, laborId={}", merchantId, laborId, e);
            return null;
        }
    }
    
    @Override
    public Page<com.campus.help.vo.LaborApplicationVO> getLaborApplications(Long laborId, Long merchantId, Integer page, Integer size) {
        Page<com.campus.help.vo.LaborApplicationVO> voPage = new Page<>();
        
        try {
            // 验证劳务是否存在且属于该商户
            com.campus.help.entity.Labor labor = laborMapper.selectById(laborId);
            if (labor == null || !merchantId.equals(labor.getMerchantId())) {
                log.error("劳务不存在或无权访问: laborId={}, merchantId={}", laborId, merchantId);
                voPage.setCurrent(page);
                voPage.setSize(size);
                voPage.setTotal(0);
                voPage.setRecords(new java.util.ArrayList<>());
                return voPage;
            }
            
            // TODO: 这里需要根据实际的申请表来查询
            // 暂时返回空列表
            voPage.setCurrent(page);
            voPage.setSize(size);
            voPage.setTotal(0);
            voPage.setRecords(new java.util.ArrayList<>());
            
            log.info("获取劳务申请列表: laborId={}, merchantId={}, total={}", laborId, merchantId, 0);
            
        } catch (Exception e) {
            log.error("获取劳务申请列表异常: laborId={}, merchantId={}", laborId, merchantId, e);
            voPage.setCurrent(page);
            voPage.setSize(size);
            voPage.setTotal(0);
            voPage.setRecords(new java.util.ArrayList<>());
        }
        
        return voPage;
    }
    
    @Override
    public boolean reviewApplication(Long applicationId, Long merchantId, String status, String reviewNote) {
        try {
            // TODO: 这里需要根据实际的申请表来实现审核逻辑
            // 1. 查询申请记录
            // 2. 验证申请对应的劳务是否属于该商户
            // 3. 更新申请状态和审核意见
            
            log.info("审核劳务申请: applicationId={}, merchantId={}, status={}", 
                applicationId, merchantId, status);
            
            // 暂时返回成功
            return true;
            
        } catch (Exception e) {
            log.error("审核劳务申请异常: applicationId={}, merchantId={}", applicationId, merchantId, e);
            return false;
        }
    }
    
    @Override
    public Merchant updateMerchantInfo(Merchant merchant) {
        try {
            // 更新时间
            merchant.setUpdateTime(LocalDateTime.now());
            
            // 不允许修改的字段保持为 null，MyBatis Plus 会忽略 null 字段
            merchant.setPassword(null);
            merchant.setStatus(null);
            merchant.setCreateTime(null);
            merchant.setLoginCount(null);
            merchant.setLastLoginTime(null);
            
            int updateCount = merchantMapper.updateById(merchant);
            
            if (updateCount > 0) {
                log.info("更新商户信息成功: merchantId={}", merchant.getId());
                // 重新查询返回完整信息
                return merchantMapper.selectById(merchant.getId());
            } else {
                log.error("更新商户信息失败: merchantId={}", merchant.getId());
                throw new RuntimeException("更新商户信息失败");
            }
            
        } catch (Exception e) {
            log.error("更新商户信息异常: merchantId={}", merchant.getId(), e);
            throw new RuntimeException("更新商户信息失败: " + e.getMessage());
        }
    }
}